<?php
/*
 * @Date: 2022-10-23 08:36:13
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-07-18 09:17:24
 */

namespace Ldy\Controller;

use Ldy\Controller\BaseAdmin;
use Ldy\Lib\Form;
use Ldy\Models\SysConfig;
use think\Request;
use Ldy\Model;
use Ldy\Facade\ClientConfig;

class Setting extends BaseAdmin{


    protected function form(){

        $form = new Form(new SysConfig());

        $data = $form->model()->select();

        $values = [];
        if(!$data->isEmpty()){
            foreach($data as $item){
                $values[$item->type] = $item->fields;
            }
        }

        $form->setFormData($values,'sys')->group('系统设置',function(Form $form) use ($values){

            $form->text('name','系统名称')->value();

            $form->switch('open_login', '登录开关')->value();

            $form->text('api_url', '接口地址')->value()->placeholder('无特殊情况一般不需要填写');
        },'sys');

        //扩展网站配置
        $extendSetting = config('admin.extend.setting');
        if($extendSetting) $form = $extendSetting::form($form, $values);
        

        return $form;
    }

    //重写保存
    /**
     * {"POST":"修改/保存系统设置"}
     * @param Request $request
     * @return void
     */
    public function store(Request $request)
    {
        $postData = $request->post();

        if(empty($postData)) $this->errorJson('非法操作！');

        foreach($postData as $key =>$item){
            $config = SysConfig::where('type', $key)->find();
            if(isset($item['id'])) unset($item['id']);
            if(isset($item['__pk'])) unset($item['__pk']);
            if($config){
                $config->fields = $item;
                $config->save();
            }else{
                SysConfig::create(['type'=>$key,'fields'=>$item]);
            }
        }

        ClientConfig::generateConfig();

        return $this->successJson('保存成功！');

    }

}